package zl.controller;

import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import zl.bean.Category;
import zl.bean.Novel;
import zl.bean.RespBean;
import zl.bean.User;
import zl.service.NovelService;
import zl.service.UserService;

import javax.servlet.http.HttpServlet;
import javax.validation.constraints.NotNull;
import java.sql.SQLException;
import java.util.List;

@Controller
@RequestMapping("/api/novel")
@Validated
public class NovelController extends HttpServlet {

    @Autowired
    private UserService userService;
    @Autowired
    private NovelService novelService;

    @GetMapping("/page")
    @ResponseBody
    public RespBean selectByPage(@NotNull(message = "当前页面不能为空") Integer currentPage, String keyword) throws SQLException {
        PageInfo<Novel> page = novelService.selectByPage(currentPage, keyword);
        return RespBean.ok("查询成功",page);
    }

    @PostMapping("/add")
    @ResponseBody
    public RespBean addNovel(@RequestBody @Validated Novel novel){
        int i = novelService.addNovel(novel);
        if(i==1){
            return RespBean.ok("添加成功");
        }else if(i==3){
            return RespBean.error("账号或用户名重复，请重新填写");
        }else {
            return RespBean.error("添加失败");
        }
    }


    @GetMapping("/{id}")
    @ResponseBody
    public RespBean selectById(@PathVariable @NotNull(message = "小说id不能为空") Integer id){
        Novel novel = novelService.selectById(id);
        return RespBean.ok("查询成功",novel);
    }


    @PostMapping("/update")
    @ResponseBody
    public RespBean updateNovel(@RequestBody @Validated Novel novel){
        int i =novelService.updateNovel(novel);
        if(i==1){
            return RespBean.ok("修改成功");
        }else{
            return RespBean.error("修改失败");
        }
    }


    @DeleteMapping("/{id}")
    @ResponseBody
    public RespBean deleteNovel(@PathVariable @NotNull(message = "小说id不能为空") Integer id){
        int i = novelService.deleteNovel(id);
        if(i==1){
            return RespBean.ok("删除成功");
        }else{
            return RespBean.error("删除失败");
        }
    }


    @GetMapping("/category")
    @ResponseBody
    public RespBean selectCategory(){
        List<Category> list=novelService.selectAllCategory();
        System.out.println("===================");
        list.forEach(System.out::println);
        if(list!=null){
            return RespBean.ok("类别查询成功",list);
        }else{
            return RespBean.error("类别失败");
        }
    }

    @GetMapping("/author")
    @ResponseBody
    public RespBean selectAuthor(){
        List<User> users = userService.selectAllUser();
        if(users!=null){
            return RespBean.ok("作者查询成功",users);
        }else{
            return RespBean.error("作者失败");
        }
    }

}
